package com.robotserver.orders.config;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import redis.clients.jedis.JedisPoolConfig;

/**
 * @author liuqi
 * @date 2022年11月17日 15:20
 */
@Configuration
public class RedisCacheConfig {
    @Value("${spring.redis-cache.host}")
    private String host; // ip
    @Value("${spring.redis-cache.port}")
    private int port; // 端口
    @Value("${spring.redis-cache.password}")
    private String password; // 密码
    @Value("${spring.redis-cache.database}")
    private int database;//数据库索引
    @Value("${spring.redis-cache.timeout}")
    private int timeout; //链接超时
    @Value("${spring.redis-cache.maxIdle}")
    private int maxIdle;// 最大空闲连接
    @Value("${spring.redis-cache.minIdle}")
    private int minIdle;// 最小空闲连接
    @Value("${spring.redis-cache.maxTotal}")
    private int maxTotal;// 连接池最大连接数（使用负值表示没有限制）

    //注入字符串缓存实例，同理可注入Object缓存实例等等
    @Bean(name = "stringRedisTemplate")
    public StringRedisTemplate StringRedisTemplate() {
        StringRedisTemplate temple = new StringRedisTemplate();
        temple.setConnectionFactory(connectionFactory());
        // 设置 key 的序列化
        temple.setKeySerializer(RedisSerializer.string());
        temple.setHashKeySerializer(RedisSerializer.string());
        // 设置 value 的序列化
        // 创建 JSON 序列化工具
        GenericJackson2JsonRedisSerializer jsonRedisSerializer = new GenericJackson2JsonRedisSerializer();
        temple.setValueSerializer(jsonRedisSerializer);
        temple.setHashValueSerializer(jsonRedisSerializer);
        return temple;
    }

    public RedisConnectionFactory connectionFactory() {
        JedisConnectionFactory jedis = new JedisConnectionFactory();
        jedis.setHostName(host);
        jedis.setPort(port);
        jedis.setTimeout(timeout);
        if (!StringUtils.isEmpty(password)) {
            jedis.setPassword(password);
        }
        if (database != 0) {
            jedis.setDatabase(database);
        }
        jedis.setPoolConfig(poolCofig());
        // 初始化连接pool
        jedis.afterPropertiesSet();

        return jedis;
    }

    public JedisPoolConfig poolCofig() {
        JedisPoolConfig poolCofig = new JedisPoolConfig();
        poolCofig.setMaxIdle(maxIdle);
        poolCofig.setMinIdle(minIdle);
        poolCofig.setMaxTotal(maxTotal);
        return poolCofig;
    }
}
